import { flattenAsyncRouter } from '@/utils/auth'
import { asyncRouter } from '@/router'

// 后台获取路由信息
const arrList = [
  {
    id: 1, name: 'Nested', child: [
      {
        id: 1, name: 'Menu1', child: [
          {id: 2, name: 'Menu1-1', child: []},
          // {id: 3, name: 'Menu1-2', child: [
          //   {id: 4, name: 'Menu1-2-1', child: [
          //     {id: 41, name: 'Menu1-2-1-1', child: []} // 无四级
          //   ]}, // 第三级一个存在bug
          //   {id: 5, name: 'Menu1-2-2', child: []},
          // ]},
          // {id: 6, name: 'Menu1-3', child: []},
        ]
      },
      // { id: 7, name: 'Menu2', child: [] },
    ]
  },
  { id: 9, name: 'Link', child: [] }
]
const flattenList = flattenAsyncRouter(arrList)

/**
 * 
 * @param {*every route} route 通过meta/other flag 来确立permission
 * @param {*需要路由|一维数组[routerName]} flattenList 
 */

function hasPermission(route, flattenList) {
  if (route.meta && route.meta.title) {
    return flattenList.some(
      v => v.trim().toLowerCase() === route.meta.title.trim().toLowerCase()
    )
  } else {
    return true
  }
  // if(route.meta.roles.includes['admin']) {
  //   return true
  // }
}

/**
 * 
 * @param {*异步所有路由} asyncRouter 
 * @param {*需要路由|一维数组[routerName]} flattenList 
 */
function filterRouter(asyncRouter, flattenList) {
  // console.log(asyncRouter, flattenList)
  const filRouters = asyncRouter.filter(route => {
    if (hasPermission(route, flattenList)) {
      if (route.children && route.children.length) {
        route.children = filterRouter(route.children, flattenList)
      }
      return true
    }
    return false
  })
  return filRouters
}

export const filRouters = filterRouter(asyncRouter, flattenList)

